import json
import re
import time

import requests

import configReader
import dataParse
import dataParseNew
import stories
from requests.cookies import cookiejar_from_dict
from bs4 import BeautifulSoup
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By


def getDatas(host, departure, arrival, date):
    # 定义请求的URL
    url = 'https://' + host + '/flights/' + departure + '-' + arrival + '/' + date + '?sort=bestflight_a'

    browser = webdriver.Chrome()

    # 发送GET请求
    browser.get(url)
    xpath = "//*[contains(@aria-label, 'Open main navigation') or contains(@aria-label, '開啟主選單')]"
    element = browser.find_element(By.XPATH, xpath)
    element.click()
    time.sleep(3)

    xpath = "//*[contains(@aria-label, 'Malaysian ringgit ') or contains(@aria-label, '新臺幣 ')]"

    element2 = browser.find_element(By.XPATH, xpath)
    element2.click()
    time.sleep(1)

    xpath_selector = "//li[contains(., 'United States dollar') or contains(., '美元')]"
    element3 = browser.find_element(By.XPATH, xpath_selector)
    element3.click()
    time.sleep(1)

    xpath_selector = "//div[text()='One time only' or text()='僅限本次使用']"
    element4 = browser.find_element(By.XPATH, xpath_selector)
    element4.click()
    time.sleep(3)

    # cookies = browser.get_cookies()
    #
    # cCookies = []
    #
    # for cookie in cookies:
    #     if cookie['domain'] == host:
    #         cCookies.append(cookie['name']+'='+cookie['value'])
    #
    # # cookieStr = ';'.join(cCookies)


    response = browser.page_source

    browser.close()

    # 解析网页内容
    soup = BeautifulSoup(response, 'html.parser')
    # 找到id为__R9_HYDRATE_DATA__的script标签
    script_tag = soup.find('script', {'type': 'application/json'})
    # 检查是否找到了标签，并打印其内容
    if script_tag:
        # 获取标签内的文本内容
        script_content = script_tag.text
        content_dict = json.loads(script_content)
        searchUrl = '/flights/' + departure + '-' + arrival + '/' + date

        if 'serverData' in content_dict:
            serverData = content_dict['serverData']
            if 'FlightResultsList' in serverData:
                FlightResultsList = serverData['FlightResultsList']
                return dataParseNew.parseFlightResults(searchUrl, FlightResultsList)
        print(departure + '-' + arrival + " 没有找到对应的数据")
        return []
    else:
        print(departure + '-' + arrival + " 没有找到对应的数据")
        return []
